<?php
namespace App\Http\Controllers\Api\Admin;

use Illuminate\Http\Request;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use App\Http\Controllers\Api\Admin\BaseController;
use App\Models\Admin;
use Illuminate\Support\Facades\Redis;


class AuthController extends BaseController
{
    /**
     * The authentication guard that should be used.
     *
     * @var string
     */
    public function __construct()
    {
        parent::__construct();
    }

    protected $return = array(
        'code' => 1,
        'msg' => ''
    );

    /**
     * 登录验证
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request,Admin $user)
    {
        $username = $request->get('username');
        $payload = [
            'name' => $username,
            'password' => md5(md5($request->get('password')))
        ];
        try {
            if (!$token = JWTAuth::attempt($payload)) {
                $this->return['msg'] = '账号密码错误';
                return response()->json($this->return, 200);// 认证失败
            }
        } catch (JWTException $e) {
            $this->return['msg'] = '无法创建token';
            return response()->json($this->return, 500);
        }
        $user_info = $user->getDataByUsername($username);
        $this->return = array(
            'code' => 0,
            'msg' => '登录成功！',
            'data' => array(
                'user_info' => $user_info,
                'token' => $token,
            )
        );
        return response()->json($this->return);
    }

    /**
     * 初始化后台管理
     * @param  Request $request [description]
     * @param  Admin   $user    [description]
     * @return [type]           [description]
     */
    public function initAdmin(Request $request,Admin $user){
        // $str = '01234567890';
        // d(strstr($str,'123456'));
        if ($user->count()>0) {
            $this->return['msg'] = '非法操作';
            return response()->json($this->return, 500);
        }
        $data = array(
            'name' => 'admin',
            'email' => 'tianming2015@foxmail.com',
            'password' => bcrypt(md5(md5('admin168'))),
            'role' => 1,
            'nick_name' => '超级管理员'
        );
        $result = $user->add_data($data);
        if ($result) {
            $this->return['code'] = 0;
            $this->return['msg'] = '操作成功';
        }else{
            $this->return['msg'] = '操作失败';
        }
        return response()->json($this->return);
    }

}
